﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Atosenet.Data
{
    public abstract class PayloadItem : IRawData, IVerifiable
    {
        #region 初始化

        public PayloadItem(byte[] data)
        {
            RawData = data;
            IsValid = Verify();
        }

        public PayloadItem()
        {
            RawData = new byte[0];
            IsValid = false;
        }

        #endregion


        #region 公开函数

        public virtual bool Verify()
        {
            return VerifyIntegrity(RawData) && ParseContent(RawData);
        }

        public override string ToString()
        {
            return "PayloadItem";
        }

        public virtual string ToString(string para)
        {
            if (string.IsNullOrEmpty(para))
                return ToString();

            switch (para.ToUpper())
            {
                case "L":
                    return string.Format("{0}[{1}]", ToString(), DataLength.ToString());
                case "D":
                    return GetDetailInfo();
                default:
                    return ToString();
            }
        }

        #endregion


        #region 静态函数

        public static bool IsNullOrInvalid(PayloadItem pItem)
        {
            return pItem == null || !pItem.IsValid;
        }

        #endregion


        #region 核心函数

        protected abstract string GetDetailInfo();

        protected virtual bool VerifyIntegrity(byte[] data)
        {
            return data != null && (IsFixedFormat ? data.Length == DataLength : data.Length >= DataLength);
        }

        protected abstract bool ParseContent(byte[] data);

        #endregion


        #region 属性

        public byte[] RawData
        {
            get;
            protected set;
        }

        public bool IsValid
        {
            get;
            protected set;
        }

        public virtual int DataLength
        {
            get { return RawData.Length; }
        }

        public virtual bool IsFixedFormat
        {
            get { return true; }
        }

        #endregion
    }
}
